package db

import (
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"poem-server/comm/global"
	"poem-server/initialize/config"
	"poem-server/mvc/dao/model"
)

func MySQLInit() {
	// mysql 配置
	var (
		user     = config.Config.Mysql.User
		password = config.Config.Mysql.Password
		host     = config.Config.Mysql.Host
		port     = config.Config.Mysql.Port
		dbname   = config.Config.Mysql.Dbname
	)

	// 连接mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, dbname)
	fmt.Println(dsn)
	var err error
	global.App.Mysql, err = gorm.Open(mysql.New(mysql.Config{
		//mysql 配置
		DSN: dsn,
	}), &gorm.Config{
		//gorm 配置
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		log.Panic("mysql数据库连接错误~", err)
	}
	log.Println("===========>mysql数据库init~", global.App.Mysql)
	//initMySqlTables(global.App.Mysql)
}

func initMySqlTables(db *gorm.DB) {
	err := db.AutoMigrate(
		model.Medium{},
	)
	if err != nil {
		global.App.Log.Error("migrate table failed", zap.Any("err", err))
		os.Exit(0)
	}
}
